package utils

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	uuid "github.com/satori/go.uuid"
	"log"
	"math/rand"
	"os"
	"os/exec"
	"strconv"
	"strings"
	"time"
)

func ToJsonStr(data interface{}) string {
	jsonBytes, err := json.Marshal(data)
	if err != nil {
		log.Println(err)
	}
	return string(jsonBytes)
}

func StringToInt64(str string, defaultValue int64) int64 {
	num, error := strconv.ParseInt(str, 10, 64)
	if error != nil {
		num = defaultValue
	}
	return num
}

func StringToInt32(str string, defaultValue int64) int32 {
	num, error := strconv.ParseInt(str, 10, 32)
	if error != nil {
		num = defaultValue
	}
	return int32(num)
}

func StringToBool(str string, defaultValue bool) bool {
	num, error := strconv.ParseBool(str)
	if error != nil {
		num = defaultValue
	}
	return num
}

func StringToFloat64(str string, defaultValue float64) float64 {
	num, error := strconv.ParseFloat(str, 64)
	if error != nil {
		num = defaultValue
	}
	return num
}

func JoinString(format string, a ...interface{}) string {
	return fmt.Sprintf(format, a...)
}

func ParseJson(jsonStr string, v interface{}) {
	// 读取的数据为json格式，需要进行解码
	err := json.Unmarshal([]byte(jsonStr), v)
	if err != nil {
		return
	}
}

func MakeKey(l int) string {
	ctx := md5.New()
	ctx.Write([]byte(uuid.NewV1().String()))
	md5Str := hex.EncodeToString(ctx.Sum(nil))
	str := "23456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + md5Str
	bytes := []byte(str)
	var result []byte
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

func Decimal(value float64) float64 {
	value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
	return value
}

func ContainsValue(list []string, value string) bool {
	for i := 0; i < len(list); i++ {
		if list[i] == value {
			return true
		}
	}
	return false
}
func RootPath() string {
	s, err := exec.LookPath(os.Args[0])
	if err != nil {
		log.Panicln("发生错误", err.Error())
	}
	i := strings.LastIndex(s, "\\")
	path := s[0 : i+1]
	return strings.ReplaceAll(path, "\\", "/")
}

func GetAppName() string {
	s, err := exec.LookPath(os.Args[0])
	if err != nil {
		log.Panicln("发生错误", err.Error())
	}
	i := strings.LastIndex(s, "\\")
	path := s[i+1 : ]
	return strings.ReplaceAll(path, "\\", "/")
}
